package com.carryGo.service.hzl;

import com.carryGo.dao.hzl.BaseDao;
import com.carryGo.entity.PageManager;
import com.carryGo.entity.User;

import java.util.List;

/**
 * ClassName:UserService
 * package:com.carryGo.service.hzl
 * Description:
 *
 * @Date:2020/8/24 14:27
 * @Author: tank_黄志凌
 */
public class UserService extends BaseDao {
    /**
     * 增加用户数据
     * @param user
     * @return
     */
    public boolean addUser(User user) {
            String sql = "INSERT INTO `rz1217db_4`.`user`(`username`, `password`, `salt`,`phone`) " +
                    "VALUES (?, ?, ?, ?)";
            Object[]params = getObjArr(user);
            return update(sql,params) > 0;
    }


    private Object[] getObjArr(User user) {
        Object[]params =
                {
                        user.getUsername(),user.getPassword(),user.getPassword(),user.getSalt()
                };
        return params;
    }

    /**
     * 分页查询
     * @param pm
     * @return
     */
    public List<User> queryUsers(PageManager pm) {
        int start = (pm.getPn() - 1) * pm.getRn();
        int end = pm.getRn();
        String sql = "select * from user limit ?,?";
        return findList(User.class, sql, start, end);
    }

    public boolean delUser(int id) {
//      String sql = "delete from user where id = ?";
        User user = queryUser(id);
        boolean result = false;
        try {
            result = delete(new User(id))> 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public User queryUser(int id) {
//        String sql = "select * from user where id = ?";
        try {
            return (User) query(new User(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean updateUser(User user) {
       /* String sql = "UPDATE `rz1217`.`user` SET `username` = ?, `password` = ?," +
                " `name` = ?, `sex` = ?, `age` = ?, `birthday` = ?, `phone` = ?, " +
                "`height` = ?, `pic` = ? WHERE `id` = ?";
        Object[] params = {user.getUsername(), user.getPassword(), user.getName(),
                user.getSex(), user.getAge(), user.getBirthday(), user.getPhone(), user.getHeight(),
                user.getPic(), user.getId()};*/
        //查询单条数据
        User queryUser = queryUser(user.getId());
        boolean result = false;
        try {
            result = update(user) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    public int queryUserTotalCount() {
        String sql = "select count(*) from user";
        return count(sql);
    }

    /**
     * 通过用户名查询用户数据
     * @param username 要查询的用户名
     * @return
     */
    public User queryUserByUsername(String username) {
        String sql = "select * from user where username = ?";
        return findBean(User.class, sql, username);
    }
}
